﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Dynamic;
using Newtonsoft.Json;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Project.Api;
using Project.Model;
using Project.BLL;
using Project.BLL.UsersInfoBll;
using Project.API.Models.UsersModels;

namespace Project.API.Controllers
{
    public class SignUsersController : ApiController
    {
        public class LoginModel
        {
            public string UserName { get; set; }
            public string Pwd { get; set; }
            public string ActiveTab { get; set; }
            public string Mobile { get; set; }
        }
        [HttpPost]
        public dynamic SignIn(LoginModel loginModel)
        {
            //密钥
            string JwtKey = ConfigurationManager.AppSettings["JwtKey"];
            //过期周期
            string JwtExp = ConfigurationManager.AppSettings["JwtExp"];

            //过期时间
            var exp = string.IsNullOrWhiteSpace(JwtExp) ? 30 : int.Parse(JwtExp);


            dynamic data = new ExpandoObject();

            user_info user = ValidateUser(loginModel);
            if (user != null)
            {
                UsersInfoDto info = new UsersInfoDto
                {
                    user_id = user.user_id,
                    username = user.username,
                    mobile = user.mobile,
                    email = user.email,
                    address = user.address,
                    points = Convert.ToInt32(user.points),
                    create_time =Convert.ToDateTime( user.create_time),
                    
                };

                try
                {
                    //加密方式
                    IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                    //序列化方式
                    IJsonSerializer serializer = new JsonNetSerializer();
                    //编码方式
                    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                    //声明Jwt
                    IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

                    //生成Token
                    var token = encoder.Encode(info, JwtKey);
                    info.Token = token;

                    data.msg = "登录成功";
                    data.data = info;
                    data.code = 1;
                }
                catch (Exception ex)
                {
                    data.msg = ex.Message;
                    data.code = -2;
                }



            }
            else
            {
                data.code = -1;
                data.msg = "账户或者密码错误！";
            }
            return data;

        }

        private user_info ValidateUser(LoginModel loginModel)
        {
            UsersInfoBll bll = new UsersInfoBll();
            loginModel.Pwd = MD5Helper.Md5(loginModel.Pwd, "X2");
            user_info info = bll.LoginUsers(loginModel.UserName, loginModel.Pwd, loginModel.ActiveTab, loginModel.Mobile);
            if (loginModel.ActiveTab == "phone")
            {
                if (info == null)
                {
                    try
                    {
                        //添加一条用户记录
                        user_info list = new user_info();
                        list.mobile = loginModel.Mobile;
                        list.username = "用户" + loginModel.Mobile.Substring(7); //随机用户名
                        list.password_hash = MD5Helper.Md5("123", "X2");
                        list.email = $"user_{loginModel.Mobile.Substring(7)}@example.com"; // 生成一个临时邮箱
                        list.points = 10;//注册默认赠送10积分
                        list.create_time = DateTime.Now;
                        list.is_delete = false;
                        bool bol = bll.Add(list);
                        return bol ? list : null;
                    }
                    catch
                    {
                        return null;
                    }


                }
            }
            return info;
        }
    }
}